const { Controller } = require('egg');
const crypto = require('crypto');
class UserController extends Controller {
  async reg() {
    // 用户注册
    const { ctx, app } = this;
    ctx.validate(
      {
        // 参数验证
        username: {
          type: 'string',
          required: true,
          range: {
            min: 1,
            max: 20
          },
          desc: '用户名'
        },
        password: {
          type: 'string',
          required: true,
          desc: '密码'
        },
        repassword: {
          type: 'string',
          required: true,
          desc: '确认密码'
        },
        email: {
          type: 'string',
          required: false,
          format: 'email',
          desc: '邮箱'
        }
      },
      {
        equals: [['password', 'repassword']]
      }
    );

    const { username, password, email } = ctx.request.body;

    const findUser = await app.model.User.findOne({
      // 查询用户名是否存在
      where: {
        username
      }
    });
    if (findUser) {
      ctx.throw(400, '用户名已存在');
    } else {
      const encryptPassword = ctx.encrypt(password, crypto);
      const user = await app.model.User.create({
        // 创建用户
        username,
        email,
        password: encryptPassword
      });
      if (!user) {
        ctx.throw(400, '注册失败');
      }
      ctx.success('注册成功');
    }
  }
  async login() {
    // 用户登录
    const { ctx, app } = this;
    const { username, password } = ctx.request.body;
    ctx.validate({
      // 参数验证
      username: {
        type: 'string',
        required: true,
        range: {
          min: 4,
          max: 16
        },
        desc: '用户名'
      },
      password: {
        type: 'string',
        required: true,
        desc: '密码'
      }
    });
    const user = await app.model.User.findOne({
      // 查询用户名是否存在是否被禁用
      where: {
        username,
        status: 1
      }
    });
    if (!user) {
      ctx.throw(400, '用户名不存在或被禁用');
    }
    // 确定密码是否正确
    const newUser = JSON.parse(JSON.stringify(user));
    const encryptPassword = ctx.encrypt(password, crypto);
    if (newUser.password !== encryptPassword) {
      ctx.throw(400, '密码错误');
    } else {
      const token = ctx.getToken(newUser); // 生成token
      newUser.token = token; // 保存token
      // 返回信息
      delete newUser.password;
      // 加入缓存中
      const redis = await this.service.cache.set('user_' + newUser.id, token);
      if (!redis) {
        ctx.throw(400, '登录失败');
      }
      // 返回信息
      ctx.success(newUser);
    }
  }
  async logout() {
    // 用户退出
    const { ctx, service } = this;
    // 1. 获得用户的id
    const { id } = ctx.authUser;
    // 2. 删除缓存中的token
    const cacheToken = service.cache.remove('user_' + id);
    if (cacheToken === 'ok') {
      ctx.fail('退出失败');
    } else {
      ctx.success('退出成功');
    }
  }
  // 获得指定用户的信息
  async getUserInfo() {
    const { ctx, app } = this;
    const id = ctx.authUser.id;
    const user_id = ctx.params.user_id;
    const user = await app.model.User.findOne({
      where: { id: user_id, status: 1 }
    });
    if (!user) {
      ctx.throw(400, '用户不存在');
    }
    ctx.success(user);
  }
  // 生成个人二维码
  async createUserCode() {
    const { ctx, app } = this;
    const id = ctx.authUser.id;
    // 1. 参数验证
    ctx.validate({
      user_id: { type: 'int', required: true, desc: '个人id' }
    });
    const { user_id } = ctx.params;
    // 查看用户是否存在
    const user = await app.model.User.findOne({
      where: { id: user_id, status: 1 }
    });
    if (!user) {
      ctx.throw(400, '用户不存在');
    }
    // 生成个人二维码
    ctx.generateQRCode(
      JSON.stringify({
        type: 'user',
        user_id: user.id,
        name: user.nickname ? user.nickname : user.userename,
        avatar: user.avatar
      })
    );
  }
  async editUserAvatar() {
    // 修改用户头像
    const { ctx, app } = this;
    const id = ctx.authUser.id;
    // 参数验证
    ctx.validate({ avatar: { type: 'string', required: true, desc: '头像' } });
    const { avatar } = ctx.request.body;
    // 查询用户是否存在
    const user = await app.model.User.findOne({
      where: {
        id,
        status: 1
      }
    });
    if (!user) {
      ctx.throw(400, '用户不存在');
    }
    // 修改头像
    user.avatar = avatar;
    await user.save();
    ctx.success('修改成功');
  }
  async editUserInfo() {
    // 修改用户信息
    const { ctx, app } = this;
    const id = ctx.authUser.id;
    // 参数验证
    ctx.validate({
      nickname: {
        type: 'string',
        required: false,
        desc: '昵称'
      },
      email: {
        type: 'email',
        required: false,
        desc: '邮箱'
      },
      phone: {
        type: 'phone',
        required: false,
        desc: '手机号'
      },
      area: {
        type: 'string',
        required: false,
        desc: '地区'
      },
      sign: {
        type: 'string',
        required: false,
        desc: '签名'
      }
    });
    const { nickname, email, phone, area, sign } = ctx.request.body;
    // 查看用户是否存在
    const user = await app.model.User.findOne({ where: { id, status: 1 } });
    if (!user) {
      ctx.throw(400, '用户不存在');
    } else {
      user.nickname = nickname ? nickname : '';
      user.email = email ? email : '';
      user.phone = phone ? phone : '';
      user.area = area ? area : '';
      user.sign = sign ? sign : '';
      await user.save();
    }
    ctx.success('修改成功');
  }
}

module.exports = UserController;
